package com.atguigu.eduservice.service.impl;

import com.atguigu.commonutils.R;
import com.atguigu.eduservice.client.VodClient;
import com.atguigu.eduservice.entity.EduVideo;
import com.atguigu.eduservice.mapper.EduVideoMapper;
import com.atguigu.eduservice.service.EduVideoService;
import com.atguigu.servicebase.handler.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author ryan
 * @since 2021-10-12
 */
@Service
public class EduVideoServiceImpl extends ServiceImpl<EduVideoMapper, EduVideo> implements EduVideoService {

    @Autowired
    private VodClient vodClient;

    @Override
    public void removeVideoByCourseId(String id) {
        QueryWrapper<EduVideo> wrap = new QueryWrapper<>();
        wrap.eq("course_id", id);
        wrap.select("video_source_id");
        List<EduVideo> eduVideos = baseMapper.selectList(wrap);
        ArrayList<String> ids = new ArrayList<>();
        for (EduVideo eduVideo : eduVideos) {
            if (eduVideo != null) {
                String videoSourceId = eduVideo.getVideoSourceId();
                if(!StringUtils.isEmpty(videoSourceId)){
                    ids.add(videoSourceId);
                }
            }
        }
        if(ids.size() > 0){
            vodClient.removeBatch(ids);
        }
        QueryWrapper<EduVideo> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id", id);
        baseMapper.delete(wrapper);
    }

    @Override
    public void removeVideo(String id) throws GuliException {
        EduVideo eduVideo = baseMapper.selectById(id);
        String videoSourceId = eduVideo.getVideoSourceId();
        if(!StringUtils.isEmpty(videoSourceId)){
            R result = vodClient.removeAliyunVideoById(videoSourceId);
            if(result.getCode() == 20001){
                throw new GuliException(20001, result.getMessage());
            }
        }
        baseMapper.deleteById(id);
    }
}
